package com.cysion.study.ui

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.text.format.DateFormat
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.darkTextTheme
import com.cysion.other.color
import com.cysion.other.startActivity_ex
import com.cysion.targetfun._subscribe
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.R
import com.cysion.study.entity.AttEntity
import com.cysion.study.helper.UserCache
import com.cysion.study.net.ApiClient
import com.cysion.study.widget.ShowToast
import kotlinx.android.synthetic.main.activity_attendence.*


//打卡
class AttendenceActivity : BaseActivity(), View.OnClickListener {

    override fun getLayoutId(): Int = R.layout.activity_attendence

    override fun initView() {
        darkTextTheme(color(R.color.main_cl))
        topbar.apply {
            setTitle("我要打卡")
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }
        val sysTime = System.currentTimeMillis()//获取系统时间
        val sysTimeStr = DateFormat.format("HH:mm:ss", sysTime)//时间显示格式  //HH:24小时制  hh:12小时制
        tv_time.text = sysTimeStr //更新时间
        Glide.with(this).load(UserCache.userInfo?.headImageUrl)
            .apply(RequestOptions.placeholderOf(R.mipmap.place_holder))
            .into(iv_head)
        tv_userName.text = UserCache.userInfo?.nickName
        ll_clock.setOnClickListener(this)
        TimeThread().start() //启动显示时间线程
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.ll_clock -> {
                //speed 打卡进度 0.上班打卡 1.下班打卡 2.今日打卡已完成(已存在下班打卡的情况)
                // 3.未开始打卡(当前时间不允许打卡,这个参数用来判断)
                if (speed == "2") {
                    ShowToast("今日已打卡")
                    return
                }
                //isCan":0,//是否可以打卡 0.正常打卡 1.外勤打卡
                if (isCan == "0") {
                    sendClock()
                } else if (isCan == "1") {

                    if (isRequestLocError()) {
                        ShowToast("获取经纬度失败，请检查定位")
                        return
                    }


                    //当前不在考勤范围内
                    var bundle = Bundle()
                    bundle.putString("speed", speed)
                    startActivity_ex<ClockinMapActivity>("key", bundle)
                } else {
                    ShowToast("不能打卡")
                    return
                }

            }
        }
    }

    private fun isRequestLocError(): Boolean {
        return "4.9E-324" == UserCache.lat ||"0.0" == UserCache.lat || "4.9E-324" == UserCache.lon || TextUtils.isEmpty(UserCache.lat) || TextUtils.isEmpty(
            UserCache.lon
        )
    }

    private fun sendClock() {
        Alert.loading(self)
        ApiClient.api.clockIn(UserCache.token, "", UserCache.lon, UserCache.lat, UserCache.cacheAddress)
            .compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    ShowToast("打卡成功")
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }

    }

    override fun initData() {
        super.initData()
        getTeacherAtt()
    }

    private fun getTeacherAtt() {
        Alert.loading(self)
        ApiClient.api.getTeacherAtt(UserCache.token, UserCache.lon, UserCache.lat)
            .compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    initview(it)
                }
                _onError {
                    Alert.close()
                    //isCan":0,//是否可以打卡 0.正常打卡 1.外勤打卡   2不能打卡
                    isCan = "2"
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }

    var speed: String = ""
    var isCan: String = "" //isCan":0,//是否可以打卡 0.正常打卡 1.外勤打卡

    private fun initview(obj: AttEntity) {
        //打卡进度 0.上班打卡 1.下班打卡 2.今日打卡已完成(已存在下班打卡的情况)
        // 3.未开始打卡(当前时间不允许打卡,这个参数用来判断)
        speed = obj.clockInfo.speed
        isCan = obj.isCan
        if (speed == "0") {
            tv_type.text = "上班打卡"
            tv_clock.text = "上班打卡"
        } else if (speed == "1") {
            tv_type.text = "下班打卡"
            tv_clock.text = "下班打卡"
        } else if (speed == "2") {
            //category":0,//打卡类型 0.上班打卡 1.下班打卡
            tv_type.text = "已打卡"
            tv_data.visibility = View.VISIBLE//打卡时间
            tv_address.visibility = View.VISIBLE//打卡地址
            tv_data.text = "打卡时间" + obj.clockInfo?.upWork?.createTime
            tv_address.text = obj.address

            tv_clock.text = "今日已打卡"
            tv_scope.visibility = View.GONE
        }

        //isCan":0,//是否可以打卡 0.正常打卡 1.外勤打卡
        if (obj.isCan == "0") {
            tv_scope.visibility = View.GONE
        } else {
            tv_scope.text = "当前不在考勤范围内"
        }

    }


    internal inner class TimeThread : Thread() {
        override fun run() {
            do {
                try {
                    Thread.sleep(1000)
                    val msg = Message()
                    msg.what = 1  //消息(一个整型值)
                    mHandler.sendMessage(msg)// 每隔1秒发送一个msg给mHandler
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }

            } while (true)
        }
    }

    //在主线程里面处理消息并更新UI界面
    private val mHandler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                1 -> {
                    val sysTime = System.currentTimeMillis()//获取系统时间
                    val sysTimeStr = DateFormat.format("HH:mm:ss", sysTime)//时间显示格式
                    tv_time.text = sysTimeStr //更新时间

                }
                else -> {
                }
            }
        }
    }

    override fun closeMvp() {
    }

}
